﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Mbs;
using Mbs.Messaging;

namespace MBTest
{
    class Actor
    {
        static IMessageBus MB = new MessageBus();

        public static void Post<TMessage>(string topic, TMessage message)
        {
            MB.Publish<TMessage>(topic,message);
        }

        public static void Post<TMessage>(string topic,object sender, TMessage message)
        {
            MB.Publish<TMessage>(topic, sender,message);
        }

        public static void Receive<TMessage>(string topic, ObserverHandler<Topic<TMessage>> handler)
        {
            MB.Subscribe<TMessage>(topic, handler);
        }

        public static void Unreceive<TMessage>(string topic, ObserverHandler<Topic<TMessage>> handler)
        {
            MB.Unsubscribe<TMessage>(topic, handler);
        }

        public static void Exit<TMessage>(string topic)
        {
            MB.Remove<Topic<TMessage>>(topic);
        }
    }

     class Topics
     {
        public const string Ping = "Topic://PingPongTest/Ping";
        public const string Pong = "Topic://PingPongTest/Pong";
     }

    [TestFixture]
    public class PingPongTest
    {
        private class Ping
        {
            int m_count = 5;
            public Ping()
            {
                Actor.Receive<Pong>(Topics.Pong, (s, e) =>
                {
                    Console.WriteLine("Ping received pong");

                    if (--this.m_count > 0)
                        Actor.Post<Ping>(Topics.Ping, this);
                    else
                    {
                        Console.WriteLine("Finished");
                        Actor.Exit<Ping>(Topics.Ping);
                    }
                });
            }

            public void Start()
            {
                Actor.Post<Ping>(Topics.Ping, this);
            }
        }

        private class Pong
        {
            public Pong()
            {
                Actor.Receive<Ping>(Topics.Ping, (s, e) =>
                {
                    Console.WriteLine("Pong received ping");
                    Actor.Post<Pong>(Topics.Pong, this);
                });
            }
        }

        [Test]
        public void Test()
        {
            var ping = new Ping();
            var pong = new Pong();
            ping.Start();
        }
    }

   
    
}
